package com.peakmain.baselibrary.recyclerview.layoutmanager;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

/**
 * author: peakmain
 * createdata：2019/7/29
 * mail: 2726449200@qq.com
 * desiption:自定义layoutManager
 */
public class CardLayoutManager extends RecyclerView.LayoutManager {
    private int mShowViewMax;
    /**
     * 每个卡片相对于上一个卡片的缩放大小
     */
    private float mSectionScale;
    /**
     * 每个卡片
     */
    private float mSectionTranslation;

    public CardLayoutManager() {
        this(10, 0.075f, 10f);
    }

    public CardLayoutManager(int showViewMax, float sectionScale, float sectionTranslation) {
        mShowViewMax = showViewMax;
        mSectionScale = sectionScale;
        mSectionTranslation = sectionTranslation;
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        super.onLayoutChildren(recycler, state);
        if (getItemCount() <= 0 || state.isPreLayout()) {
            return;
        }
        //先移除所有的view
        detachAndScrapAttachedViews(recycler);

        int itemCount = getItemCount();
        if (getItemCount() > mShowViewMax) {
            itemCount = mShowViewMax;
        }
        //　这里要注意view要反着加，因为adapter position = 0对应的view我们要显示在最上层
        for (int position = itemCount - 1; position >= 0; position--) {
            //获取指定位置的view
            View view = recycler.getViewForPosition(position);
            addView(view);
            //测量view
            measureChildWithMargins(view, 0, 0);
            //view在recyclerview里面剩余的空间
            int widthSpace = getWidth() - getDecoratedMeasuredWidth(view);
            //居中显示
            int heightSpace=getHeight()-getDecoratedMeasuredHeight(view);
            //摆放
            layoutDecoratedWithMargins(view, widthSpace / 2, heightSpace/2, widthSpace / 2 + getDecoratedMeasuredWidth(view)
                    , heightSpace/2+getDecoratedMeasuredHeight(view));
            // 为了让重叠在一起的view，有一个更好的显示效果
            view.setScaleX(getScaleX(position));
            view.setScaleY(getScaleY(position));
            view.setTranslationX(getTranslationX(position));
            view.setTranslationY(getTranslationY(position));
        }
    }

    private float getScaleX(int position) {
        return 1f - position * mSectionScale;
    }

    private float getScaleY(int position) {
        return 1f;
    }

    private float getTranslationX(int position) {
        return 0f;
    }

    private float getTranslationY(int position) {
        return -position * mSectionTranslation;
    }

}
